from rest_framework import serializers
from .models import  Inform,InformRead
from apps.oaauth.serializers import UserSerializer,DepartmentSerializer
from .models import OADepartment

class InformReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformRead
        fields = '__all__'

class InformSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    department = DepartmentSerializer(read_only=True,many=True)
    department_ids = serializers.ListField(write_only=True)
    reads = InformReadSerializer(many=True,read_only=True)  ## 只展示不验证

    class Meta:
        model = Inform
        fields = '__all__'
        read_only_fields = ['public',]

    ## 重新 保存Inform对象的 create 方法
    def create(self,validated_data):
        request = self.context.get('request')
        department_ids = validated_data.pop('department_ids')
        department_ids = list(map(lambda value:int(value),department_ids))
        if 0 in department_ids:
            inform = Inform.objects.create(public=True,author=request.user,**validated_data)
        else:
            departments = OADepartment.objects.filter(id__in=department_ids).all()
            inform = Inform.objects.create(public=False,author=request.user,**validated_data)
            inform.department.set(departments)
            inform.save()
        return inform



class ReadInformSerializer(serializers.Serializer):
    inform_pk = serializers.IntegerField(error_messages={"required":"请传入 inform 的 id"})
